package com.sscl.blesample.activity.guide;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.NotificationManagerCompat;

import com.sscl.baselibrary.activity.BaseWelcomeActivity;
import com.sscl.baselibrary.utils.BaseManager;
import com.sscl.baselibrary.utils.CrashHandler;
import com.sscl.baselibrary.utils.PermissionUtil;
import com.sscl.baselibrary.utils.ToastUtil;
import com.sscl.blesample.R;
import com.sscl.blesample.activity.main.MainActivity;


/**
 * @author jacke
 */
public class WelcomeActivity extends BaseWelcomeActivity {

    /*-----------------------成员变量-----------------------*/

    private static final int PERMISSION_REQUEST_CODE = 1;


    private boolean needCheckPermission;

    private String[] permissions = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
    };

    @TargetApi(Build.VERSION_CODES.S)
    private String[] permissionsS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_ADVERTISE
    };

    @TargetApi(Build.VERSION_CODES.Q)
    private String[] permissionsQ = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
    };
    private PermissionUtil.OnPermissionRequestResult onRequestPermissionsResult = new PermissionUtil.OnPermissionRequestResult() {

        /**
         * 权限请求成功
         */
        @Override
        public void permissionRequestSucceed() {
            toNext();
        }

        /**
         * 权限请求失败
         *
         * @param failedPermissions 请求失败的权限
         */
        @Override
        public void permissionRequestFailed(String[] failedPermissions) {
            toSettingActivity();
        }
    };

    /*-----------------------实现父类函数-----------------------*/

    @Override
    protected void doAfterAnimation() {
        checkPermission();
    }

    /**
     * 设置ImageView的图片资源
     *
     * @return 图片资源ID
     */
    @Override
    protected int setImageViewSource() {
        return 0;
    }

    /*-----------------------重写父类函数-----------------------*/

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * Dispatch onResume() to fragments.  Note that for better inter-operation
     * with older versions of the platform, at the point of this call the
     * fragments attached to the activity are <em>not</em> resumed.
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (!needCheckPermission) {
            return;
        }
        needCheckPermission = false;
        checkPermission();
    }

    /*-----------------------自定义函数-----------------------*/

    /**
     * 检查权限
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            NotificationManagerCompat manager = NotificationManagerCompat.from(WelcomeActivity.this.getApplicationContext());
            boolean isOpened = manager.areNotificationsEnabled();
            if (!isOpened) {
                ToastUtil.toastLong(WelcomeActivity.this, R.string.no_notification_permission);
                //去打开通知权限
                showOpenNotificationPermissionDialog();
                return;
            }
        }

        boolean hasPermissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            hasPermissions = PermissionUtil.hasPermissions(this, permissionsS);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            hasPermissions = PermissionUtil.hasPermissions(this, permissionsQ);
        } else {
            hasPermissions = PermissionUtil.hasPermissions(this, permissions);
        }
        if (hasPermissions) {
            toNext();
        } else {
            requestPermissions();
        }
    }

    /**
     * 请求权限
     */
    private void requestPermissions() {
        PermissionUtil.setOnPermissionRequestResult(onRequestPermissionsResult);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PermissionUtil.requestPermission(this, PERMISSION_REQUEST_CODE, permissionsS);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            PermissionUtil.requestPermission(this, PERMISSION_REQUEST_CODE, permissionsQ);
        } else {
            PermissionUtil.requestPermission(this, PERMISSION_REQUEST_CODE, permissions);
        }
    }

    /**
     * 进入主界面
     */
    private void toNext() {
        //权限完全请求并获取完毕后，初始化全局异常捕获类
        CrashHandler.getInstance().init(getApplicationContext());
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 跳转到设置中，让用户打开通知权限
     */
    private void showOpenNotificationPermissionDialog() {
        new AlertDialog.Builder(WelcomeActivity.this)
                .setTitle(R.string.no_notification_permission_title)
                .setMessage(R.string.no_notification_permission_message)
                .setPositiveButton(R.string.allow, (dialogInterface, i) -> {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getApplication().getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                })
                .setNegativeButton(R.string.cancel, (dialogInterface, i) -> checkPermission())
                .setCancelable(false)
                .show();

    }

    /**
     * 跳转到设置中，让用户打开权限
     */
    private void toSettingActivity() {
        PermissionUtil.toSettingActivity(this);
        BaseManager.getHandler().postDelayed(() -> needCheckPermission = true, 500);
    }
}
